import App from './App'
import {
	createPinia
} from 'pinia';
import uviewPlus, {
	setConfig
} from 'uview-plus'


// #ifndef VUE3
import Vue from 'vue'
import './uni.promisify.adaptor'

Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
	...App
})
app.$mount()
// #endif

// #ifdef VUE3
import {
	createSSRApp
} from 'vue'
// 全家混入分享功能
import share from "@/mixins/share.js"
import {
	API_CONFIG
} from '@/utils/interceptors.js'

export function createApp() {
	const app = createSSRApp(App)

	app.use(uviewPlus, () => {
		return {
			options: {
				// 修改$u.config对象的属性
				config: {
					// 修改默认单位为rpx，相当于执行 uni.$u.config.unit = 'rpx'
					unit: 'rpx',
					iconUrl: 'https://at.alicdn.com/t/font_2225171_8kdcwk4po24.ttf'
				}
			}
		}
	})
	const pinia = createPinia();
	app.use(pinia);

	let isNavigating = false
	const white = ['/wechat/schemeDataSend'];
	// 请求拦截器
	uni.$u.http.interceptors.request.use((config) => {

		let isWhite = white.includes(config.url);
		config.url = API_CONFIG.baseUrl + config.url;
		const openid = uni.getStorageSync('openid') || 'owcFGvn55hwOIXTPx6qILBs-zJH4';
		const isLogin = uni.getStorageSync('isLogin'); // 登录状态标记
		if (openid&&!isWhite) {
			if (['post', 'put'].includes(config.method.toLowerCase())) {
				// POST和PUT放入请求体中
				if (typeof config.data === 'object' && config.data !== null) {
					config.data.openid = openid;
				} else {
					config.data = {
						openid
					};
				}
			} else {
				// 其他的直接拼接URL
				const separator = config.url.includes('?') ? '&' : '?';
				config.url += `${separator}openid=${openid}`;
			}
			// if (!isLogin && getCurrentPages().pop().route !== 'pages/login/login') {
			// 	if (!isNavigating) {
			// 		isNavigating = true;

			// 		// 延迟跳转，避免立即跳转打断当前请求
			// 		setTimeout(() => {
			// 			uni.navigateTo({
			// 				url: '/pages/login/login',
			// 				success: () => {
			// 					isNavigating = false;
			// 				},
			// 				fail: (err) => {
			// 					console.error('跳转首页失败:', err);
			// 					isNavigating = false;
			// 				}
			// 			});
			// 		}, 300);
			// 	}
			// 	// 取消当前请求
			// 	return Promise.reject(new Error('请先登录'));
			// }
		}
		config.header = {
			...config.header,
			'Authorization': uni.getStorageSync('openid') || '',
			'Content-Type': 'application/json;charset=utf-8'
		}
		return config
	})

	// 响应拦截器
	uni.$u.http.interceptors.response.use((response) => {
		const {
			data
		} = response;
		const {
			body
		} = data || {};
		const {
			success,
			message
		} = body || {};
		if (success) {
			return body;
		} else {
			uni.$u.toast(message || '请求失败，请稍后重试');
			return Promise.reject(message || '请求失败，请稍后重试');
		}
	})
	app.mixin(share)
	return {
		app
	}
}

// #endif